package com.ncmem.utils;

import com.ncmem.model.FileInf;
import com.ncmem.model.Up7Exception;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

public class UtilsTool {

    /// <summary>
    /// sm4-cbc-pkcs7padding-块对齐大小
    /// </summary>
    public static int sm4AlignBlockSize(int blockSize){
        int len = blockSize % 16;
        len = 16 - len;
        return blockSize + len;
    }

    /**
     * 解压缩
     * @param s
     * @param f
     * @return
     * @throws Up7Exception
     */
    public static ByteArrayOutputStream unCompress(ByteArrayOutputStream s, FileInf f) throws Up7Exception {
        //未压缩
        if(0==f.blockSizeCpr) return s;

        if(s.size() != f.blockSizeCpr)
            throw new Up7Exception(f,s,"接收的块大小与发送的块大小不一致");
        if (f.blockCprType.equalsIgnoreCase("zip") ) return unZip(s);
        return unGzip(s);
    }

    public static ByteArrayOutputStream decrypt(ByteArrayOutputStream s, FileInf f) throws Up7Exception {

        int blockSize = f.blockSize;
        //开启了加密
        if(f.blockEncrypt) blockSize = f.blockSizeCry;

        //块大小不同
        if(blockSize != s.size())
            throw new Up7Exception(f,s,"发送的块大小与接收的块大小不同");

        //未加密
        if(!f.blockEncrypt) return s;
        //启用存储加密
        if(f.encrypt) return s;

        CryptoTool ct = new CryptoTool();
        return ct.decrypt(f.encryptAgo,s);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="s"></param>
    /// <param name="type">gzip,zip</param>
    /// <returns></returns>
    public static ByteArrayOutputStream unGzip(ByteArrayOutputStream s) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(s.toByteArray());
        try
        {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int n;
            while ((n = ungzip.read(buffer)) >= 0)
            {
                out.write(buffer, 0, n);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return out;
    }

    public static ByteArrayOutputStream unZip(ByteArrayOutputStream s) {
        ByteArrayInputStream bin =new ByteArrayInputStream(s.toByteArray());
        InflaterInputStream iis = new InflaterInputStream(bin);
        ByteArrayOutputStream o = new ByteArrayOutputStream();

        try {

            byte[] buf = new byte[1024];
            int i=0;

            while ((i = iis.read(buf)) > 0) {
                o.write(buf, 0, i);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return o;
    }
}
